/**
 * Created by doucharles1 on 16/4/9.
 */
var _=require("underscore")
var async=require("async")
var util=require("util")
var ObjectID=require("mongodb").ObjectID
var path=require("path")
$load("FileManager.js")
$load("MyUtil.js")

var objDonationColl=$objMongoColls["maindb"]["donation"]
var objDonationUserColl=$objMongoColls["maindb"]["donation_user"]
var objDonationUsageColl=$objMongoColls["maindb"]["donation_usage"]
var objUserColl=$objMongoColls["maindb"]["user"]
var objBadgeColl=$objMongoColls["maindb"]["badge"]

/*
donation:{
    type:<int>     //0：后台发布     1：客户端发布的提议性募捐
    _id:<ObjectID>     //募捐ID，
    img_logo:<string>,
    img_multi_posters:[
        <string>,
        ...
    ],
    subject:<string>     //募捐主题
    description:<string>,
    dt_publish:<Datetime>
    dt_sync:<Datetime>,
    dt_end:<Datetime>，
    _id_badge:<ObjectID>,
    target_amount:0,
    cur_donation_amount:0,
    cur_usage_amount:0,
    cur_usage_num:0,
    cur_donation_loves:0,
    status:2          //募捐状态 0：待审核 1：审核失败 2：募捐中 3：募捐结束
    failure_reason:"",
    _id_publish_user:<ObjectID>
}

badge:{
    _id:<ObjectID>,
    img_logo:""
    subject:"募捐徽章",
    origin:"",
    dt_create:<Datetime>,
    binding:{
        "collection":"activity",
        "_id":<ObjectID>
    },
    _id_publish_user:<ObjectID>
}
 */
$dao["donation"]["insertOneDonation"]=function(objDonation,funcCb){
    var dtNow=new Date()
    var objDefault={
        type:0,
        img_logo:"",
        img_multi_posters:[],
        subject:"",
        description:"",
        dt_publish:dtNow,
        dt_sync:dtNow,
        dt_end:new Date(),
        target_amount:0,
        cur_donation_amount:0,
        cur_usage_amount:0,
        cur_usage_num:0,
        cur_donation_num:0,
        cur_donation_loves:0,
        status:2,
        failure_reason:""
    }

    objDefault=_.extend(objDefault,objDonation)
    if(objDefault["type"]==1){
        objDefault["status"]=2
    }

    $dao["cmn"].insertOne("maindb","donation",objDefault,function(errcode,objInsertedID){
        funcCb(errcode,objInsertedID)
    })
}

$dao["donation"]["updateOneDonation"]=function(objDonationID,objUpdated,funcCb){
    var dtNow=(new Date()).getTime()
    async.waterfall([
        function(cb){
            objDonationColl.findOne({_id:objDonationID},{fields:{_id:0,status:1,dt_end:1}},function(err,objDonation){
                if(err){
                    req.junkfiles=[objUpdated["img_logo"]].concat(objUpdated["img_multi_posters"])
                    cb({errcode:1001},null)
                }else if(!objDonation || objDonation["dt_end"].getTime()<dtNow || objDonation["status"]==3){
                    req.junkfiles=[objUpdated["img_logo"]].concat(objUpdated["img_multi_posters"])
                    cb({errcode:11001},null)
                }else{
                    cb(null,null)
                }
            })
        },
        function(lastResult,cb){
            objDonationColl.findOneAndUpdate({_id:objDonationID},
                {$set:objUpdated,$currentDate:{dt_sync:true}},
                {projection:{_id:0,status:1,cur_donation_amount:1,cur_donation_num:1,cur_donation_loves:1,cur_usage_amount:1},returnOriginal:false},
                function(err,uResult){
                    if(err){
                        req.junkfiles=[objUpdated["img_logo"]].concat(objUpdated["img_multi_posters"])
                        cb({errcode:1001},null)
                    }else{
                        req.junkfiles=[uResult["value"]["img_logo"]].concat(uResult["value"]["img_multi_posters"])
                        cb(null,uResult["value"])
                    }
                })
        }
    ],funcCb)
}

$dao["donation"]["detailOneDonation"]=function(objDonationID,funcCb){
    objDonationColl.findOne({_id:objDonationID},function(err,objSearched){
        if(err){
            funcCb(1001,null)
        }else{
            if(objSearched["_id_badge"]){
                objBadgeColl.findOne({_id:objSearched["_id_badge"]},{fields:{_id:0,img_logo:1,subject:1,origin:1}},function(err,objBadge){
                    if(err){
                        funcCb(1001,null)
                    }else{
                        objSearched["img_badge_logo"]=objBadge["img_logo"]
                        objSearched["badge_subject"]=objBadge["subject"]
                        objSearched["badge_origin"]=objBadge["origin"]
                        funcCb(0,objSearched)
                    }
                })
            }else{
                funcCb(null,objSearched)
            }
        }
    })
}

$dao["donation"]["syncDonations"]=function(page,perpage,objFilter,objSort,funcCb){
    var objOptions={
        coll:"donation",
        page:page,
        pagesize:perpage,
        objFilter:objFilter,
        sort:objSort,
        projection:{
            failure_reason:0,
            _id_badge:0,
            _id_publish_user:0
        }
    }
    $dao["cmn"]["syncPage"](objOptions,funcCb)
}
/*
donation_usage:{
    _id:<ObjectID>,
    _id_donation:<ObjectID>
    img_multi_posters:<string>,
    subject:<string>,
    description:<string>,
    dt_publish:<Datetime>,
    dt_sync:<Datetime>
    amount:<int>,
    _id_publish_user:<ObjectID>
}
 */

$dao["donation"]["insertDonationUsage"]=function(objDonationID,userid,objInserted,funcCb){
    objInserted["_id_donation"]=objDonationID
    objInserted["dt_publish"]=objInserted["dt_sync"]=new Date()
    objInserted["_id_publish_user"]=userid
    var result={_id:null}
    async.waterfall([
        function(cb){
            objDonationUsageColl.insertOne(objInserted,function(err,iResult){
                if(err){
                    req.junkfiles=objInserted["img_multi_posters"]
                    cb({errcode:1001},null)
                }else{
                    result["_id"]=iResult["insertedId"]
                    cb(null,null)
                }
            })
        },
        function(lastResult,cb){
            objDonationColl.updateOne({_id:objDonationID},{$inc:{cur_usage_num:1,cur_usage_amount:objInserted["amount"]},$currentDate:{dt_sync:true}},function(err,uResult){
                    if(err){
                        req.junkfiles=objInserted["img_multi_posters"]
                        cb({errcode:1002},null)
                    }else{
                        cb(null,result)
                    }
                })
        }
    ],funcCb)
}

$dao["donation"]["updateDonationUsage"]=function(objDonationUsageID,userid,objUpdated,funcCb){
    objUpdated["_id_publish_user"]=userid
    var oldAmount=0
    objDonationUsageColl.findOneAndUpdate({_id:objDonationUsageID},{$set:objUpdated,$currentDate:{dt_sync:true}},{projection:{_id:0,_id_donation:1,img_multi_posters:1,amount:1}},function(err,uResult){
        if(err){
            req.junkfiles=objUpdated["img_multi_posters"]
            oldAmount=uResult["value"]["amount"]
            funcCb(1001,null)
        }else{
            req.junkfiles=uResult["value"]["img_multi_posters"]
            objDonationColl.updateOne({_id:uResult["value"]["_id_donation"]},{$inc:-oldAmount},function(err,uResult){
                if(err){
                    funcCb(1001,null)
                }else{
                    objDonationColl.updateOne({_id:uResult["value"]["_id_donation"]},{$inc:objUpdated["amount"]},function(err,uResult){
                        if(err){
                            funcCb(1001,null)
                        }else{
                            funcCb(null,null)
                        }
                    })
                }
            })
        }
    })
}

$dao["donation"]["syncDonationUsages"]=function(objDonationID,page,perpage,objFilter,objSort,funcCb){
    objFilter["_id_donation"]=objDonationID
    var objOptions={
        coll:"donation_usage",
        page:page,
        pagesize:perpage,
        descending:false,
        objFilter:objFilter,
        sort:objSort,
        projection:{
            _id_publish_user:0
        }
    }
    $dao["cmn"]["syncPage"](objOptions,funcCb)
}

$dao["donation"]["userDonate"]=function(objCharge,funcCb){
    async.waterfall([
        function(cb){
            objDonationUserColl.count({userid:objCharge["metadata"]["userid"]},function(err,count){
                if(err){
                    cb({errcode:1001},false)
                }else{
                    if(count!=0){
                        cb(null,false)
                    }else{
                        cb(null,true)
                    }
                }
            })
        },
        function(boolUserDonated,cb){
            objUserColl.findOne({_id:objCharge["metadata"]["userid"]},{fields:{_id:0,img_:1,nickname:1}},function(err,objUser){
                if(err){
                    cb({errcode:1001},null)
                }else{
                    cb(null,boolUserDonated,objUser["img_headportrait"],objUser["nickname"])
                }
            })
        },
        function(boolUserDonated,strImg,strNickName,cb){
            var objUpdated={$inc:{cur_donation_amount:objCharge["amount"],cur_donation_loves:1}}
            if(!boolUserDonated){
                objUpdated["$inc"]["cur_donation_num"]=1
            }
            objUpdated["$set"]={
                img_user_headportrait:strImg,
                user_nickname:nickname
            }
            objDonationColl.findOneAndUpdate({_id:new ObjectID(objCharge["order_no"])},objUpdated,{returnOriginal:false},function(err,objResult){
                if(err){
                    cb({errcode:1002},null)
                }else{
                    var objCache=$cache.load("donation","donation_usage_statistics")
                    if(!objCache["cur_donation_amount"]){
                        objCache["cur_donation_amount"]=0
                    }
                    if(!objCache["cur_donation_num"]){
                        objCache["cur_donation_num"]=0
                    }
                    if(!objCache["cur_donation_loves"]){
                        objCache["cur_donation_loves"]=0
                    }
                    objCache["cur_donation_amount"]+=objCharge["amount"]
                    ++objCache["cur_donation_num"]
                    ++objCache["cur_donation_loves"]
                    $cache.refresh("donation","donation_usage_statistics",objCache)
                    cb(null,null)
                }
            })
        }
    ],function(err,objResult){
        if(err){
            funcCb(err["errcode"])
        }else{
            funcCb(0)
        }
    })
}

$dao["donation"]["userDonateValidate"]=function(req,funcCb){
    var now=$cmn["myutil"]["now"]()
    objDonationColl.findOne({_id:new ObjectID(req.params.orderno)},{fields:{_id:0,state:1,dt_end:1}},function(err,objResult){
        if(err){
            funcCb(1001)
        }else if(objResult["state"]==1 || now>=objResult["dt_end"]){
            objDonationColl.updateOne({_id:new ObjectID(req.params.orderno)},{$set:{
                state:1
            }},function(err,objResult){
                if(err){
                    funcCb(1002)
                }else{
                    funcCb(11001)
                }
            })
        }else{
            funcCb(0)
        }
    })
}

$dao["donation"]["syncDonationUsers"]=function(objDonationID,page,perpage,objFilter,objSort,funcCb){
    
}
